//  this library.
import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
// import 'package:hktk_app/dao/login_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/util/encrypt_util.dart';

import 'package:http/http.dart' as http;
import 'package:http/http.dart';
import 'package:logging/logging.dart';

import 'my_util.dart';
import 'package:hktk_app/dao/login_dao.dart';

/// 请求工具类

/// 图片路径请求头
const String coverHead = "http://yun-cdn.caishi.cn/";

/// 下载路径起始
const String downPath = "中震网校";

/// gid ase加密
String _gidAes = "";

/// 获取政策数据对应url的key值
const int _groupId = 6; // 中震网校








// static const int _groupId = 5;


/// 请求头
// const String httpDomainName = "http://10.0.2.2:8880";























// const String httpDomainName = "https://sub.zzwx.cn";
const String httpDomainName = "http://www.zzwx.cn:8083";



//
// const String httpDomainName = "http://192.168.0.116:26001";
// const String httpDomainName = "https://api-test.yunxuebao.com";
// const String httpDomainName = "https://api-pro.yunxuebao.com";

const String cTypeX = "application/x-www-form-urlencoded;";
const String cTypeJson = "application/json;";
// http://plus.zzwx.cn/cdn/app-release.apk
/// 返回值对应标签
const String resMsg = "message";
const String resApi = "apiDown";
const String resCode = "code";
const String resData = "data";
const String resSuc = "success";

/// 进行解码方法
String utf8decoderC(Response response) {
  Utf8Decoder utf8decoder = const Utf8Decoder();
  return utf8decoder.convert(response.bodyBytes);
}

/// 解码并返回 map方法
Map<String, dynamic> jsonDecodeMap(Response response) {
  String bodyString = utf8decoderC(response);
  return json.decode(bodyString);
}


/// 获取gid方法
int getGroupId() {
  return _groupId;
}

/// 获取加密gid方法
String _getAesGid() {
  if (_gidAes == "") {
    _gidAes = EncryptUtil.gidAesEncrypt(data: _groupId.toString());
  }
  return _gidAes;
}

/// 获取请求头方法
Map<String, String> getHeaders() {
  String type = "android";
  if (Platform.isIOS) {
    type = "ios";
  } else if (Platform.isAndroid) {
    type = "android";
  }

  var token = getToken();



  Map<String, String> map = {
    "channelCode": "app",
    "Content-Type": "application/json; charset=UTF-8",
    "dt": type,
    "ht": "s",
    "gid": _getAesGid(),
    "yuntk-auth-token": token ?? "",
  };
  return map;
}

/// 获取超时时间，默认5秒
Duration getTimeOut({int? sec}) {
  return Duration(seconds: sec ?? 120);
}

/// http GET 请求方法
Future<dynamic> httpGET({required String url, String tips = ""}) async {
  try {
    // 封装url
    Uri uri = Uri.parse(httpDomainName + url);
    // 发送请求
    var response =
    await http.get(uri, headers: getHeaders()).timeout(getTimeOut());
    // 解析数据
    return getResponse(
      response: response,
      type: "GET",
      tips: tips,
      url: uri.toString(),
    );
  } on TimeoutException {

    // 监听超时异常
    throw DaoException(msg: "请求超时，请重试", code: -1);
  }
}
Future<dynamic> httpGET1({required String url,required Map<String, dynamic>  params, String tips = ""}) async {
  try {
    // 封装url
    Uri uri = Uri.parse(httpDomainName + url).replace(queryParameters: params);

    var response =
    await http.get(uri, headers: getHeaders()).timeout(getTimeOut());
    // 解析数据
    return getResponse(
      response: response,
      type: "GET",
      tips: tips,
      url: uri.toString(),
    );
  } on TimeoutException {
    throw DaoException(msg: "请求超时，请重试", code: -1);
  }
}

/// 解析返回数据方法
dynamic getResponse({
  required Response response,
  required String type,
  required String tips,
  required String url,
  String params = "",
}) {
  // 进行解码，避免中文乱码
  Map<String, dynamic> map = jsonDecodeMap(response);
  // 打印数据
  debugPrint(url);
  // 判断是否请求成功，根据编码
  if (response.statusCode == 200) {
    // 判断是否成功
    if (map[resSuc]) {
      return map[resData];
    } else {
      // 判断登录是否过期
      if (map[resCode] == 101) {
        // 拦截，取消登录，并进入登录页面
        LoginDao.loginOut();
        // throw DaoException(msg: "请重新登录", code: map[resCode]);
      } else {
        // 失败
        throw DaoException(msg: map[resMsg], code: map[resCode]);
      }
    }
  } else {
    throw Expanded(child: map[resMsg]);
  }
}

// custom 自定义发送数据，true：params必传，false：paramsStr必传
/// http POST 方式
Future<dynamic> httpPOST({
  required String url,
  Map<String, dynamic>? params,
  String? paramsStr,
  String tips = "",
  String contentType = cTypeJson,
  bool custom = true,
  String? encryptionType,
}) async {
  try {
    // 封装url
    if (contentType == cTypeX && custom) {
      url = _getPostCTypeXUrl(url, params!);
    }
    Uri uri = Uri.parse(httpDomainName + url);
    // 请求头
    Map<String, String> headers = getHeaders();
    headers["Content-Type"] = "$contentType charset=UTF-8";
    if (encryptionType != null) {
      headers["encryption-type"] = encryptionType;
    }
    // 将要发送的数据，json格式化
    String encode;
    if (custom) {
      encode = jsonEncode(params);
    } else {
      encode = paramsStr!;
    }
    // 发送请求
    Response response;
    if (contentType == cTypeX) {
      response = await http.post(uri, headers: headers).timeout(getTimeOut());
    } else {
      response = await http
          .post(uri, body: encode, headers: headers)
          .timeout(getTimeOut());
    }
    // 解析数据
    return getResponse(
      response: response,
      type: "POST",
      tips: tips,
      url: uri.toString(),
      params: encode,
    );
  } on TimeoutException {
    // 监听超时异常
    throw DaoException(msg: "请求超时，请重试", code: -1);
  }
}

/// 获取post请求 x-www-from-urlencoded 格式的url
String _getPostCTypeXUrl(String url, Map<String, dynamic> params) {
  bool start = true;
  var keys = params.keys;
  for (String key in keys) {
    if (start) {
      url = "$url?";
      start = false;
    } else {
      url = "$url&";
    }
    if (params[key] != null) {
      url = "$url$key=${params[key]}";
    }
  }
  return url;
}

/// http Put 方法
dynamic httpPut({
  required String url,
  required Map<String, dynamic> params,
  String tips = "",
}) async {
  try {
    // 封装url
    Uri uri = Uri.parse(httpDomainName + url);
    // 将要发送的数据，json格式化
    String encode = jsonEncode(params);
    // 发送请求
    Response response = await http
        .put(
      uri,
      headers: getHeaders(),
      body: encode,
    )
        .timeout(getTimeOut());
    // 解析数据
    return getResponse(
      response: response,
      type: "PUT",
      tips: tips,
      url: uri.toString(),
      params: encode,
    );
  } on TimeoutException {
    // 监听超时异常
    throw DaoException(msg: "请求超时，请重试", code: -1);
  }
}

/// http Delete 方式
dynamic httpDelete({
  required String url,
  required Map<String, dynamic> params,
  String tips = "",
}) async {
  try {
    // 封装url
    Uri uri = Uri.parse(httpDomainName + url);
    // 将要发送的数据，json格式化
    String encode = jsonEncode(params);
    // 发送请求
    Response response = await http
        .delete(
      uri,
      headers: getHeaders(),
      body: encode,
    )
        .timeout(getTimeOut());
    // 解析数据
    return getResponse(
      response: response,
      type: "DELETE",
      tips: tips,
      url: uri.toString(),
      params: encode,
    );
  } on TimeoutException {
    // 监听超时异常
    throw DaoException(msg: "请求超时，请重试", code: -1);
  }
}


/// http GET 请求方法
Future<dynamic> httpGETTest({required String url, String tips = ""}) async {
  try {
    final testHost="http://10.0.2.2:8080";
    Uri uri = Uri.parse(testHost + url);
    // 发送请求
    var response =
    await http.get(uri, headers: {}).timeout(Duration(seconds: 120));
    // 解析数据
    return getResponse(
      response: response,
      type: "GET",
      tips: tips,
      url: uri.toString(),
    );
  } on TimeoutException {
    // 监听超时异常
    throw DaoException(msg: "请求超时，请重试", code: -1);
  }
}

Future<dynamic> httpPOSTTest({
  required String url,
  Map<String, dynamic>? params,
  String? paramsStr,
  String tips = "",
  String contentType = cTypeJson,
  bool custom = true,
  String? encryptionType,
}) async {
  try {
    // 封装url
    if (contentType == cTypeX && custom) {
      url = _getPostCTypeXUrl(url, params!);
    }
    final testHost="http://10.0.2.2:8080";
    Uri uri = Uri.parse(testHost + url);
    // 请求头
    Map<String, String> headers = {};
    headers["Content-Type"] = "$contentType charset=UTF-8";
    if (encryptionType != null) {
      headers["encryption-type"] = encryptionType;
    }
    // 将要发送的数据，json格式化
    String encode;
    if (custom) {
      encode = jsonEncode(params);
    } else {
      encode = paramsStr!;
    }
    // 发送请求
    Response response;
    if (contentType == cTypeX) {
      response = await http.post(uri, headers: headers).timeout(Duration(seconds: 120));
    } else {
      response = await http
          .post(uri, body: encode, headers: headers)
          .timeout(getTimeOut());
    }
    // 解析数据
    return getResponse(
      response: response,
      type: "POST",
      tips: tips,
      url: uri.toString(),
      params: encode,
    );
  } on TimeoutException {
    // 监听超时异常
    throw DaoException(msg: "请求超时，请重试", code: -1);
  }
}

dynamic httpPutTest({
  required String url,
  required Map<String, dynamic> params,
  String tips = "",
}) async {
  try {
    // 封装url
    final testHost="http://10.0.2.2:8080";
    Uri uri = Uri.parse(testHost + url);
    // 将要发送的数据，json格式化
    String encode = jsonEncode(params);
    // 发送请求
    Response response = await http
        .put(
      uri,
      headers: {},
      body: encode,
    )
        .timeout(getTimeOut());
    // 解析数据
    return getResponse(
      response: response,
      type: "PUT",
      tips: tips,
      url: uri.toString(),
      params: encode,
    );
  } on TimeoutException {
    // 监听超时异常
    throw DaoException(msg: "请求超时，请重试", code: -1);
  }
}